<?php
namespace app\admin\controller;

use app\common\controller\AdminBaseController;
use think\Request;

/**
 *
 */
class ThemeController extends AdminBaseController
{
    protected $beforeActionList = [
        'before_check_post' => ['only' => 'save,startup'],
        'before_check_delete' => ['only' => 'delete'],
    ];

    protected function before_check_post()
    {
        //dump($this->request->method());
        if (!$this->request->isPost()) {
            $this->error('请使用正确的方式提交!');
        }
    }

    protected function before_check_delete()
    {
        if (!$this->request->isDelete()) {
            $this->error('请使用正确的方式提交!');
        }
    }

    /**
     * 主题列表
     * @return [type] [description]
     */
    public function index()
    {
        $keywords = $this->request->param('keywords');
        $this->assign('keywords', $keywords);

        $themes_mark = config('app.themes_mark');
        $themes_path = '.' . config('app.themes_path');
        $resource = opendir($themes_path);
        $list = [];
        while ($theme = readdir($resource)) {
            if ($theme == "." || $theme == "..") {
                continue;
            }
            if (!is_dir($themes_path . '/' . $theme)) {
                continue;
            }
            $data = $this->get_theme($themes_path . '/' . $theme);
            if (!$data) {
                continue;
            }
            // 获取标识 预览图
            $data['theme_mark'] = $theme;
            $data['theme_image'] = trim($themes_path . '/' . $theme . '/preview.png', '.');
            $data['theme_default'] = $themes_mark == $theme ? true : false;
            if ($keywords == '') {
                $list[] = $data;
                continue;
            }
            if (strpos($data['theme_name'], $keywords) !== false) {
                $list[] = $data;
                continue;
            }
            if (strpos($data['theme_mark'], $keywords) !== false) {
                $list[] = $data;
                continue;
            }
            if (strpos($data['theme_description'], $keywords) !== false) {
                $list[] = $data;
                continue;
            }
        }
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function startup(Request $request, $mark)
    {
        // 把主题标识 mark 保存到 app.setting 里面
        $data = array('themes_mark' => $mark);
        if (admin_config_app($data) === false) {
            $this->error('保存 admin/config/app.php 文件失败！');
        }
        $data = array(
            'view_path' => 'themes/' . $mark . '/',
            'tpl_replace_string' => [
                '__THEME__' => '/themes/' . $mark,
            ],
        );
        if (index_config_template($data) === false) {
            $this->error('保存 index/config/template.php 文件失败！');
        }
        $this->success('恭喜：设置主题成功！', null, '', 1);

    }

    /**
     * 保存新增
     * @return [type] [description]
     */
    public function save(Request $request)
    {
        // 主题路径
        $source = $request->param('theme_file');

        // 安装主题 成功返回:true 失败返回:false
        $result = $this->install_theme($source);
        if (!$result) {
            $this->error('错误：新增主题失败!');
        }

        // 安装完成后删除源文件
        del_file($source);

        $this->success('恭喜：主题安装成功!', null, '', 1);
    }

    /**
     * 删除
     */
    public function delete(Request $request, $mark)
    {
        // 删除主题目录
        $path = config('app.themes_path');
        $path = '.' . ltrim($path, '.');
        $path = rtrim($path, '/') . '/' . $mark;

        if (del_dir($path)) {
            $this->success('恭喜：删除成功!', null, '', 1);
        } else {
            $this->error('错误：删除失败!');
        }
    }

    /**
     * [get_theme_info 获取主题信息]
     * @param  [type] $theme [description]
     * @return [type]        [description]
     */
    private function get_theme($path)
    {
        $style_path = $path . '/style.css';
        if (!file_exists($style_path) || !is_readable($style_path)) {
            return false;
        }

        // 以只读的方式打开 style.css.
        $fp = fopen($style_path, 'r');

        // 每次读取8Kb
        $file_data = fread($fp, 8192);

        // 关闭文件连接
        fclose($fp);

        $file_data = str_replace("\r", "\n", $file_data);

        // 参考 wordpress 模板
        $data = array(
            'theme_name' => 'Theme Name',
            'theme_uri' => 'Theme URI',
            'theme_description' => 'Description',
            'theme_author' => 'Author',
            'theme_author_uri' => 'Author URI',
            'theme_version' => 'Version',
            'theme_tags' => 'Tags',
        );

        // 循环取出参数
        foreach ($data as $field => $regex) {
            if (preg_match('/^[ \t\/*#@]*' . preg_quote($regex, '/') . ':(.*)$/mi', $file_data, $match) && $match[1]) {
                $data[$field] = trim($match[1]);
            } else {
                $data[$field] = '';
            }
        }
        return $data;
    }

    /**
     * [install_theme 安装主题]
     * @param  [type] $filename [description]
     * @return [type]           [description]
     */
    private function install_theme($filename)
    {

        $filename = '.' . ltrim($filename, '.');

        // 先判断待解压的文件是否存在
        if (!file_exists($filename)) {
            return false;
        }

        // 主题路径
        $path = config('app.themes_path');
        $path = '.' . ltrim($path, '.');
        $path = rtrim($path, '/') . '/';

        //将文件名和路径转成windows系统默认的gb2312编码，否则将会读取不到
        /*$filename = iconv("utf-8", "gb2312", $filename);
         *$path = iconv("utf-8", "gb2312", $path);*/

        //打开压缩包
        $resource = zip_open($filename);

        //遍历读取压缩包里面的一个个文件
        while ($dir_resource = zip_read($resource)) {

            //如果能打开则继续
            if (zip_entry_open($resource, $dir_resource)) {

                //获取当前项目的名称,即压缩包里面当前对应的文件名
                $file_name = $path . zip_entry_name($dir_resource);

                //以最后一个“/”分割,再用字符串截取出路径部分
                $file_path = substr($file_name, 0, strrpos($file_name, "/"));

                //如果路径不存在，则创建一个目录，true表示可以创建多级目录
                if (!is_dir($file_path)) {
                    mkdir($file_path, 0777, true);
                }

                //如果不是目录，则写入文件
                if (!is_dir($file_name)) {

                    //读取这个文件
                    $file_size = zip_entry_filesize($dir_resource);

                    //最大读取6M，如果文件过大，跳过解压，继续下一个
                    if ($file_size < (1024 * 1024 * 30)) {
                        $file_content = zip_entry_read($dir_resource, $file_size);
                        file_put_contents($file_name, $file_content);
                    }
                }

                //关闭当前
                zip_entry_close($dir_resource);
            }
        }

        //关闭压缩包
        zip_close($resource);
        return true;
    }
}
